//
//  RequestWork.m
//  WisdomShope
//
//  Created by mac on 15/12/26.
//  Copyright (c) 2015年 ZY. All rights reserved.
//

#import "RequestWork.h"
#import "NSObject+ViewController.h"

@implementation RequestWork


#pragma mark AFN get请求（网络请求时的图片动画展示）
+ (void)afGetHttpWihtRUL:(NSString *)urlString wihtParmas:(NSDictionary *)parmas successBackBlock:(void(^)(id responsobject))successBlock fileBackBlock:(void(^)(id reponsobject))fileBlock{

    //1.创建一个请求的管理对象
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //2.设置请求参数的格式
    /**
     *  AFHTTPRequestSerializer : 将请求参数格式化为&符号拼接
     *  AFJSONRequestSerializer : 将请求参数格式化为json数据
     */
    //申明请求的数据是json类型
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    //申明返回的结果是json类型
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSNumber *user_id = [defaults objectForKey:@"user_id"];
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:parmas];
    if (user_id) {
        [dic setObject:user_id forKey:@"request_user_id"];
    }else{
        [dic setObject:@"0" forKey:@"request_user_id"];
    }
 
    [manager GET:urlString parameters:dic success:^(NSURLSessionDataTask *task, id responseObject) {
        successBlock(responseObject);

    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        fileBlock(error);
    }];
    
}
#pragma mark AFN post请求（网络请求时的图片动画展示）
+ (void)POSTOfAFNWithURL:(NSString *)url pamars:(NSDictionary *)pamars successBackBlock:(void(^)(id responsobject))successBlock fileBackBlock:(void(^)(id reponsobject))fileBlock{
 
    //1.创建一个请求的管理对象
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //2.设置请求参数的格式
    /**
     *  AFHTTPRequestSerializer : 将请求参数格式化为&符号拼接
     *  AFJSONRequestSerializer : 将请求参数格式化为json数据
     */
    
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    
    manager.responseSerializer = [AFJSONResponseSerializer serializer];

    [manager POST:url parameters:pamars success:^(NSURLSessionDataTask *task, id responseObject) {
        
        successBlock(responseObject);
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        fileBlock(error);
    }];
}
#pragma mark AFN POST请求 form data 格式
+ (void)sendWeiboUseAFNetWoringWithURL:(NSString *)url pamars:(NSDictionary *)pamars successBackBlock:(void(^)(id responsobject))successBlock fileBackBlock:(void(^)(id reponsobject))fileBlock{
    //1.创建一个请求的管理对象
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //2.设置请求参数的格式
    /**
     *  AFHTTPRequestSerializer : 将请求参数格式化为&符号拼接
     *  AFJSONRequestSerializer : 将请求参数格式化为json数据
     */
    manager.requestSerializer = [AFJSONRequestSerializer serializer];

    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    NSString *lvl = [pamars objectForKey:@"lvl"];
    UIImage *image = [UIImage imageNamed:@"find_nav_search@2x"];
    NSData *data = UIImageJPEGRepresentation(image, 0.5);
    NSData *da = [data base64EncodedDataWithOptions:NSDataBase64Encoding64CharacterLineLength];
    [manager POST:url parameters:@{@"lvl":lvl}  constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
                [formData appendPartWithFileData:da name:@"img" fileName:@"aia.jpg" mimeType:@"image/jpg"];
        
    } success:^(NSURLSessionDataTask *task, id responseObject) {
        
        successBlock(responseObject);
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        fileBlock(error);
    }];
    

    
}







+ (NSString *)parmasStringWithParmas:(NSDictionary *)parmas{
    
    NSMutableString *parmasString = [[NSMutableString alloc] init];
    
    for (NSString *key in parmas) {
        
        [parmasString appendFormat:@"%@=%@",key,[parmas objectForKey:key]];
        
        if (key != [[parmas allKeys]lastObject]) {
            
            [parmasString appendFormat:@"&"];
        }
        
    }
    
    return parmasString;
}


/*网络请求的三大步骤
 
 1. 设置请求路径 NSURL
 2. 构造一个请求对象 NSURLrequest ：请求体 请求方法 包含请求路径
 3. 发送请求11
 */

+ (void)httpRequestWithURL:(NSString *)urlString parmas:(NSDictionary *)parmas httpMethod:(NSString *)method successBackBlock:(void(^)(id responsobject))successBlock fileBackBlock:(void(^)(id reponsobject))fileBlock{
    
    //1，设置请求路径
    NSURL *rul = [NSURL URLWithString:urlString];
    //拼接传入参数
    NSString *parmasString = [self parmasStringWithParmas:parmas];
    
    //构建网络请求
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:rul];
    [request setHTTPMethod:method];
    [request setTimeoutInterval:60];

    if ([method isEqualToString:@"GET"]) {
        
        //设置请求查询的字符
        NSString *separe = rul.query?@"&":@"?";
        
        NSString *fullString = [NSString stringWithFormat:@"%@%@%@",rul,separe,parmasString];
        //改称UTF8形式
        NSURL *fullUrl = [NSURL URLWithString:[fullString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
        
        [request setURL:fullUrl];
        
    }else{
        
        [request setHTTPBody:[parmasString dataUsingEncoding:NSUTF8StringEncoding]];
    
        
    }
    
    
    //3，发送请求
    //    发送同步请求
    //    [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    //2发送异步请求
    NSOperationQueue *mainQueue = [NSOperationQueue mainQueue];
    [NSURLConnection sendAsynchronousRequest:request queue:mainQueue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        
        if (data) {
            
            id reqestob = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            
            successBlock(reqestob);
        }
        
        if (connectionError) {
            
            fileBlock((NSHTTPURLResponse*)response);
        }
        
        
    }];
    
}
#pragma mark put
+ (void)sendputwith:(NSString *)url parmas:(NSDictionary *)parmas successBackBlock:(void(^)(id responsobject))successBlock fileBackBlock:(void(^)(id reponsobject))fileBlock{
    
    //1.创建一个请求的管理对象
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

    //2.设置请求参数的格式
    /**
     *  AFHTTPRequestSerializer : 将请求参数格式化为&符号拼接
     *  AFJSONRequestSerializer : 将请求参数格式化为json数据
     */
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    
    
    [manager PUT:url parameters:parmas success:^(NSURLSessionDataTask *task, id responseObject) {
        
        successBlock(responseObject);
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        fileBlock(error);
    }];
    
}

#pragma mark 修改用户头像
+ (void)changeUserImageUseAFNetWoringWithURL:(NSString *)url pamars:(NSDictionary *)pamars successBackBlock:(void(^)(id responsobject))successBlock fileBackBlock:(void(^)(id reponsobject))fileBlock{
    //1.创建一个请求的管理对象
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //2.设置请求参数的格式
    /**
     *  AFHTTPRequestSerializer : 将请求参数格式化为&符号拼接
     *  AFJSONRequestSerializer : 将请求参数格式化为json数据
     */
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
//    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    

    [manager POST:url parameters:pamars constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        
//        NSData *data = UIImageJPEGRepresentation([pamars objectForKey:@"img"], 0.5);
//
//        [formData appendPartWithFileData:data name:@"img" fileName:@"avatar.jpg" mimeType:@"image/jpeg"];
        
    } success:^(NSURLSessionDataTask *task, id responseObject) {
        
        
        successBlock(responseObject);
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        
        fileBlock(error);
    }];
    
}
#pragma mark 上传视频POST
+ (void)upMoveWithURL:(NSString *)url pamars:(NSString *)pamars successBackBlock:(void(^)(id responsobject))successBlock fileBackBlock:(void(^)(id reponsobject))fileBlock{
    //1.创建一个请求的管理对象
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //2.设置请求参数的格式
    /**
     *  AFHTTPRequestSerializer : 将请求参数格式化为&符号拼接
     *  AFJSONRequestSerializer : 将请求参数格式化为json数据
     */
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
   
    [manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        
//        NSData *data = UIImageJPEGRepresentation(pamars, 0.5);
        NSData *_data = [NSData dataWithContentsOfFile:pamars];
        NSData *data = [[NSData alloc] initWithData:_data];
        
//        获取文件名
        NSString *fileName = [pamars lastPathComponent];
//        获取文件格式
        NSString *fileType = [pamars pathExtension];
        [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:fileType];
        
    } success:^(NSURLSessionDataTask *task, id responseObject) {
        
        
        successBlock(responseObject);
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        
        fileBlock(error);
    }];
    
}


@end
